package com.appsino.bingluo.secret;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

public class MonitorService extends Service {
    /*
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //处理任务
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                    Intent mIntent = new Intent();
                    mIntent.setAction(TestReveiver.EEEEE);
//                mIntent.putExtra("clipboardvalue", item.getText().toString());
                    sendBroadcast(mIntent);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("CommitPrefEdits")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("tag", "启动前台服务  onCreate");
        //如果API在26以上即版本为O则调用startForefround()方法启动服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            setForegroundService();
//            Intent intent = new Intent(MonitorService.this,MainActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
        }
    }

    /**
     *通过通知启动服务
     */
    @androidx.annotation.RequiresApi(api = Build.VERSION_CODES.O)
    public void  setForegroundService()
    {
        //设定的通知渠道名称
        String channelName = "测试前台服务";
        //设置通知的重要程度
        int importance = NotificationManager.IMPORTANCE_LOW;
        //构建通知渠道
        NotificationChannel channel = new NotificationChannel("1000", channelName, importance);
        channel.setDescription("cehis");
        //在创建的通知渠道上发送通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "1000");
        builder.setSmallIcon(R.mipmap.ic_launcher) //设置通知图标
                .setContentTitle("移动公证")//设置通知标题
                .setContentText("服务正在运行")//设置通知内容
                .setAutoCancel(true) //用户触摸时，自动关闭
                .setOngoing(true);//设置处于运行状态
        //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
        NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
        //将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
        startForeground(1111111,builder.build());
    }
}
